<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Model\AppChannel;
use App\Model\Banner;
use App\Model\VideoLink;
use App\Util\AliyunUtil;
use App\Util\ComUtil;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Layout\Content;

class BannerController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */

    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('首页Banner位');
            $content->description('');
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('Banner位详情');
            $content->description('');
            $content->body($this->form('edit', $id)->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('Banner位创建');
            $content->description('');
            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        Admin::style('.dt-range-showing {color:#409EFF;}');
        Admin::style('.dt-range-expired {color:#999;}');
        Admin::style('.dt-range-coming {color:#000000;}');

        $channels = AppChannel::getChannels();
        return Admin::grid(Banner::class, function (Grid $grid) use ($channels) {
            $self = $this;
            $grid->model()->orderBy('created_at', 'desc');
            $grid->id('ID');
            $grid->title('标题');
            $grid->channel('平台')->display(function ($data) {
                return Banner::CHANNEL[$data] ?? '-';
            });
            $grid->app_channel('应用渠道')->display(function ($data) use ($channels) {
                if (!$data) return '全部渠道';
                $channel = explode(',', $data);
                $str = [];
                foreach ($channel as $ch) $str[] = $channels[$ch];
                return implode('<br/>', $str);
            });
            $grid->jump_type('跳转类型')->display(function ($data) {
                $str = Banner::getJumpTypes($data);
                $str .= '<div style="color:#999;">' . json_encode(json_decode($this->jump_info), JSON_UNESCAPED_UNICODE) . '</div>';
                return $str;
            });
            $grid->poster('Banner图片')->display(function ($data) {
                return ComUtil::buidlImgaeHtml($data, 200, 100, true);
            });
            $grid->begin_at('展示时间段')->display(function () {
                $beginAt = strtotime($this->begin_at);
                $endAt = strtotime($this->end_at);
                $now = time();
                $class = $now >= $beginAt && $now <= $endAt ? 'dt-range-showing' : '';
                $class = $now > $endAt ? 'dt-range-expired' : $class;
                $class = $now < $beginAt ? 'dt-range-coming' : $class;
                return "<div class='$class'>{$this->begin_at}<br>{$this->end_at}</div>";
            });
            $grid->gender('展示性别')->display(function ($data) {
                return $data == -1 ? '不限' : ($data == 1 ? '男' : '女');
            });
            $grid->created_at('创建时间')->display(function ($time) {
                return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
            });
            $grid->flag('是否有效')->display(function ($flag) {
                return $flag ? '有效' : '无效';
            });

            //禁用导出
            $grid->disableExport();
            //禁用行选择
            $grid->disableRowSelector();
            $grid->filter(function ($filter) {
                $filter->equal('flag', '有效状态')->select([0 => '无效', 1 => '有效']);
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                // $actions->disableDelete();
                $actions->disableView();
            });
        });
    }

    /**
     * Make a form builder.
     * @return Form
     */
    protected function form($mode = '', $id = '')
    {
        return Admin::form(Banner::class, function (Form $form) use ($mode, $id) {
            $form->text('title', 'Banner标题');
            if ($id) {
                $banner = Banner::find($id);
                $jump_info = json_decode($banner->jump_info, true);
                $wx_info = json_decode($banner->wx_info,true);
            } else {
                $jump_info = json_decode($form->model()->jump_info, true);
                $wx_info = json_decode($form->model()->wx_info,true);
            }
            $form->multipleSelect('app_channel', '应用渠道')->options(AppChannel::getChannels());
            $form->select('gender', '展示性别')->options([-1 => '不限', 1 => '男', 0 => '女'])->default(-1);
            $form->image('poster', 'Banner图片')->uniqueName(); //->removable();
            $form->select('jump_type', '跳转类型')->options(Banner::getJumpTypes())->default(1);
            $form->text('link', '链接地址（H5，小程序跳转才设置）')->value(isset($jump_info['link']) ? $jump_info['link'] : '');
            $form->select('wx_id','微信选择')->options(VideoLink::getWxId())->default(0);
            $form->select('flag', '是否有效')->options([1 => '有效', 0 => '无效'])->default(1);
            $form->hidden('jump_info');
            $form->hidden('wx_info');
            $form->ignore(['link']);
            $form->select('channel', '平台')->options(Banner::CHANNEL)->default(0);
            $form->datetimeRange('begin_at', 'end_at', '有效时间段');
            $form->saving(function (Form $form) {
                $wxId = request('wx_id');
                $link = request('link');
                $form->wx_info = VideoLink::getWxInfo($wxId,$link) ?? '';
                $form->jump_info = $link ? json_encode(['link' => $link]) : '';
            });

            $form->tools(function (Form\Tools $tools) {
                // 去掉`列表`按钮
                $tools->disableList();
                // 去掉`删除`按钮
                $tools->disableDelete();
                // 去掉`查看`按钮
                $tools->disableView();
            });
        });
    }
}
